package com.qingke.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.qingke.pojo.User;

public class ChatDao {
	
	private SessionFactory sf=null;
	private Session session=null;
	
	public ChatDao(){}
      
	{
		sf=new Configuration().configure().buildSessionFactory();
		session=sf.openSession();
	}	
	
	public <T> void insert(T t){
		Transaction tx=session.beginTransaction();
		try {

			session.save(t);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	
	public Criteria getCriteria(Class<?> classType){
		DetachedCriteria detachedCriteria =DetachedCriteria.forClass(classType);
		Criteria criteria =detachedCriteria.getExecutableCriteria(session);
		return criteria;
	}
	public boolean isUserExists(String username,String password){
		 Criteria criteria=getCriteria(User.class);
		 criteria.add(Restrictions.eq("username", username));
		 criteria.add(Restrictions.eq("password", password));
		 List<?> list =criteria.list();
		 if(list.size()>0){
			 return true;
		 }
		 return false;
	}
	
	public User login(String username){
		Criteria criteria =getCriteria(User.class);
		criteria.add(Restrictions.eq("username", username));
		List<?> list =criteria.list();
		User user =null;
		if(list.size()>0){
			user=(User)list.get(0);
		}
		return user;
	}
	
	public boolean isUsernameEixsts(String username){
		Criteria criteria = getCriteria(User.class);
		criteria.add(Restrictions.eq("username", username));
		List<?> list=criteria.list();
		if(list.size()>0){
			return true;
		}
		return false;
	}
	
	public boolean register(String username,String password,String name){
		if(isUsernameEixsts(username)){
			return false;
		}
		User user =new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setName(name);
		Transaction tx=session.beginTransaction();
		try {
			session.save(user);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
			return false;
		}
		return true;
	}
	public void close(){
		session.close();
	}
	
}
